package com.fwmagic.flink.tablesql.stream;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import org.apache.flink.util.Collector;

public class StreamSQLWordCount {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        StreamTableEnvironment streamEnv = StreamTableEnvironment.create(env);

        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<String> wordsDataStream = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String line, Collector<String> out) throws Exception {
                String[] words = line.split("\\s");
                for (String word : words) {
                    out.collect(word);
                }
            }
        });

        streamEnv.registerDataStream("t_wc", wordsDataStream, "word");

        Table table = streamEnv.sqlQuery("select word,count(1) from t_wc group by word");

        DataStream<Tuple2<Boolean, Row>> dataStream = streamEnv.toRetractStream(table, Row.class);

        //dataStream.print();

        SingleOutputStreamOperator<Tuple2<Boolean, Row>> filteredDataStream = dataStream.filter(new FilterFunction<Tuple2<Boolean, Row>>() {
            @Override
            public boolean filter(Tuple2<Boolean, Row> tp) throws Exception {
                return tp.f0;
            }
        });

        filteredDataStream.print();

        env.execute("StreamSQLWordCount");

    }
}
